package com.tdam2012.grupo04;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TimeZone;

import com.tdam2012.grupo04.data.ActividadesProvider;

import android.net.Uri;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;


public class CallListActivity extends ListActivity implements OnItemClickListener {

	private NumbersAdapter _adapter;
	private static final String ESTADOCEL="Estado Cel";
	private static final String ESTMARCANDO="marcando/Activo";
	private static final String ESTENTRANTE="Llamada Entrante";
	private static final String ESTINACTIVO="Inactivo";
	private static final String TEL="tel:";
	private static final String GTM="GMT-03:00";
	private static final String FORMATO="dd/MM/yyyy HH:mm:ss";
	Contact contacto;
	TelephonyManager telMgr;
	PhoneStateListener listener;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_call_list);
        formatListView();
        cargarNumeros();
        
        telMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        
        listener = new PhoneStateListener(){
        	public void onCallStateChanged(int state, String incomingNumber){
        		super.onCallStateChanged(state, incomingNumber);
        		 switch (state) {
        	     case TelephonyManager.CALL_STATE_IDLE:
        	      Log.v(ESTADOCEL, ESTINACTIVO);
        	      break;
        	     case TelephonyManager.CALL_STATE_OFFHOOK:
        	    	 Log.v(ESTADOCEL, ESTMARCANDO);
        	         Calendar c = Calendar.getInstance(TimeZone.getTimeZone(GTM)); 
        	         SimpleDateFormat postFormater = new SimpleDateFormat(FORMATO); 
        	         	
        	         //Registro llamada
        	         ContentValues cv = new ContentValues();
    	     		 cv.put(ActividadesProvider.COL_TIPO, getString(R.string.CallListActivity_accionLlamadaSaliente));
        	     	 cv.put(ActividadesProvider.COL_ID, contacto.get_id());
        	     	 cv.put(ActividadesProvider.COL_FECHA, postFormater.format(c.getTime()));
        	     	 getContentResolver().insert(ActividadesProvider.CONTENT_URI, cv);
        	     	 
        	      break;
        	     case TelephonyManager.CALL_STATE_RINGING:
        	    	 Log.v(ESTADOCEL, ESTENTRANTE);
        	      break;
        		 }
        	}
        	
        };
        telMgr.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    
    private void formatListView() {
		_adapter = new NumbersAdapter(); 
		getListView().setAdapter(_adapter); 
		getListView().setOnItemClickListener((OnItemClickListener) this);
		
	}
    
    private void onItemSelected(int position) {
		// TODO Auto-generated method stub
    	String number =(String) _adapter.getItem(position);
    	if(number != null){
    	Intent i = new Intent(Intent.ACTION_CALL);
    	i.setData(Uri.parse(TEL+ number));
    	
		startActivity(i);
    	}
	}
    
    private void cargarNumeros() {
    	
    	 contacto = (Contact) getIntent().getSerializableExtra(ContactScreenActivity.KEY_CONTACT);
    	_adapter.setNumbers(contacto.get_numerosDeTelefono());
    	_adapter.notifyDataSetChanged();
			
		}
    
    @Override
    protected void onResume() {
    	// TODO Auto-generated method stub
    	super.onResume();
    }
    
    class Holder {
		TextView numero;
		TextView texto;
		ImageView imagen;
	}
    
	public class NumbersAdapter extends BaseAdapter{
		
		private LayoutInflater _inflater; 
		private ArrayList<String> _numbers;
		
		public NumbersAdapter() { 
			 _numbers = new ArrayList<String>(); 
			_inflater = LayoutInflater.from(CallListActivity.this);
		}
		
		
		public void setNumbers(ArrayList<String> numeros) {
			for (String number : numeros) {
				_numbers.add(number);
			}
		}
		
	
		public String setNumber(int position) {
			String number = (String) getItem(position);
			return number;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return _numbers.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return _numbers.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position ;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			Holder holder = null;
			if (convertView == null) {
				convertView = _inflater.inflate(R.layout.attr_item, null); 
				holder = new Holder();  
				holder.texto = (TextView) convertView.findViewById(R.id.txtTitulo);
				holder.numero = (TextView) convertView.findViewById(R.id.txtDato);
				holder.imagen=(ImageView) convertView.findViewById(R.id.imagen);
				
				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag(); 
			}

			
			String numero = _numbers.get(position);
            
            holder.texto.setText(R.string.CallListActivity_llamarA);
			holder.numero.setText(numero);
			holder.imagen.setImageResource(android.R.drawable.ic_menu_call);

			return convertView; 
			
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		onItemSelected(position);
	}
	
	
}


